package com.finance.system.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import com.finance.base.enums.StateEnum;
import com.finance.base.exception.BaseException;
import com.finance.system.bean.pojo.Menu;
import com.finance.system.bean.pojo.Role;
import com.finance.system.bean.pojo.RoleMenuRel;
import com.finance.system.bean.pojo.User;
import com.finance.system.dao.RoleMapper;
import com.finance.system.dao.UserRoleMapper;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by CBWL on 2017/3/17.
 */
@Service
public class RoleService implements IRoleService{

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;


    /**
     * 根据id查询角色
     * @param id
     * @return
     */
    @Override
    public Role getById(String id) {
        if(StringUtils.isEmpty(id)){
            return null;
        }
        return this.roleMapper.getById(id);
    }

    /**
     * 查询所有角色信息
     * @return
     */
    @Override
    public List<Role> listAll() {
        return this.roleMapper.listAll();
    }

    /**
     * 查询角色信息
     * @param page
     * @return
     */
    @Override
    public PageResultBO<Role> listByPage(Page page){
        PageResultBO<Role> resultBO = new PageResultBO<Role>();
        List<Role> list = this.roleMapper.listByPage(page);
        resultBO.setDataList(list);
        resultBO.setPageSize(page.getPageSize());
        resultBO.setPageNo(page.getPageNo());
        resultBO.setTotalRecord(page.getTotalRecord());
        return resultBO;
    }

    /**
     * 新增角色
     * @param role
     * @throws BaseException
     */
    @Override
    public boolean add(Role role,List<String> menuCodes) throws BaseException{
        boolean backResult = true;
        int row = this.roleMapper.add(role);
        backResult = this.updateMenuRel(role.getId(),role.getUpdateUid(),menuCodes);
        return row == 1 && backResult;
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @Override
    public boolean delete(String id) throws BaseException{
        boolean backResult = this.delRoleMenu(id);
        return this.roleMapper.delete(id) == 1 && backResult;
    }

    /**
     * 更新角色信息
     * @param role
     * @return
     * @throws BaseException
     */
    @Override
    public boolean update(Role role,List<String> menuCodes) throws BaseException{
        boolean backResult = true;
        if(menuCodes != null && menuCodes.size() >0){
            backResult = this.updateMenuRel(role.getId(),role.getUpdateUid(),menuCodes);
        }
        return this.roleMapper.update(role) == 1 && backResult;
    }

    /**
     *
     * @param role
     * @return
     */
    @Override
    public List<Menu> listMenus(Role role) {
        if(role == null|| role.getId() != 0) {
            return null;
        }
        return this.roleMapper.listMenus(role);
    }


    @Override
    public List<Role> list4User(User user) {
        return null;
    }

    /**
     * 查询传授信息
     * @param user
     * @param roleId
     * @return
     */
    @Override
    public Role query4User(User user, Long roleId) {
        if(CollectionUtils.isNotEmpty(user.getRoleList())){
            for(Role role : user.getRoleList()){
                if(role.getId().equals(roleId)) {
                    return role;
                }
            }
        }
        return null;
    }

    /**
     * 角色传授
     * @param user
     * @param authUser
     * @param role
     * @return
     */
    @Override
    public boolean add4User(User user, User authUser,Role role) {
        if(user == null) {
            return false;
        }
        if(CollectionUtils.isEmpty(user.getRoleList())){
            return this.roleMapper.add4User(user,authUser,role)==1;
        }else if(!user.getRoleList().contains(role)){
            return this.roleMapper.add4User(user,authUser,role)==1;
        }else if(this.query4User(user,role.getId()).getState()== StateEnum.Valid.getState()){
            return this.roleMapper.update4User(user,authUser,role)==1;
        }
        return false;
    }

    /**
     * 更新传授角色
     * @param user
     * @param authUser
     * @param role
     * @return
     */
    @Override
    public boolean modify4user(User user, User authUser, Role role) {
        if(user == null) {
            return false;
        }
        if(CollectionUtils.isEmpty(user.getRoleList()) || !user.getRoleList().contains(role)){
            return false;
        }else {
            return this.roleMapper.update4User(user,authUser,role) == 1;
        }
    }

    /**
     * 批量删除角色
     * @param ids
     * @return
     */
    @Override
    public boolean batchDelRole(List<String> ids) {
        return roleMapper.batchDelRole(ids) > 0;
    }

    /**
     * 根据roleId删除用户角色关系
     * @param roleId
     * @return
     */
    @Override
    public boolean delUserRole(String roleId){
        return this.userRoleMapper.delUserRole(Long.parseLong(roleId)) == 1;
    }

    /**
     * 根据roleId删除角色菜单关系
     * @param roleId
     * @return
     * @throws BaseException
     */
    @Override
    public boolean delRoleMenu(String roleId) throws BaseException{
        //// TODO: 2017/4/6
        return true;
    }

    /**
     * 删除对应用户角色关系
     */
    @Override
    public boolean deleteUserRole(String roleId) throws BaseException {
        return this.userRoleMapper.delByRoleId(Long.parseLong(roleId)) > 0;
    }

    /**
     * 配置菜单关系
     * @param roleId
     * @param uId
     * @param menuCodes
     * @return
     */
    @Override
    @Transactional
    public boolean updateMenuRel(Long roleId,Long uId,List<String> menuCodes){
        List<RoleMenuRel> roleMenuRels = roleMapper.listByRoleId(roleId);
        //需要插入的
        List<RoleMenuRel> newRels = new ArrayList<RoleMenuRel>();
        //需要更新失效的
        List<RoleMenuRel> invalidRels = new ArrayList<RoleMenuRel>();
        //需要更新有效的
        List<RoleMenuRel> validRels = new ArrayList<RoleMenuRel>();
        if(roleMenuRels != null && roleMenuRels.size() > 0){
            for (RoleMenuRel rel:roleMenuRels){
                if(menuCodes.contains(rel.getMenuCode())){
                    //包含
                    if(rel.getState()==0){
                        //包含的原来是失效的,跟新成有效的  原来有效的不管
                        RoleMenuRel roleMenuRel = new RoleMenuRel();
                        roleMenuRel.setState(StateEnum.Valid.getState());
                        roleMenuRel.setUpdateUid(uId);
                        roleMenuRel.setRoleId(roleId);
                        roleMenuRel.setMenuCode(rel.getMenuCode());
                        validRels.add(roleMenuRel);
                    }
                    //移除
                    menuCodes.remove(rel.getMenuCode());
                }else {
                    //不包含 使失效
                    RoleMenuRel roleMenuRel = new RoleMenuRel();
                    roleMenuRel.setState(StateEnum.Invalid.getState());
                    roleMenuRel.setUpdateUid(uId);
                    roleMenuRel.setRoleId(roleId);
                    roleMenuRel.setMenuCode(rel.getMenuCode());
                    invalidRels.add(roleMenuRel);
                }
            }

        }
        if(menuCodes != null && menuCodes.size() >0){
            for (String menuCode : menuCodes){
                RoleMenuRel rel = new RoleMenuRel();
                rel.setState(StateEnum.Valid.getState());
                rel.setCreateUid(uId);
                rel.setRoleId(roleId);
                rel.setMenuCode(menuCode);
                newRels.add(rel);
            }
        }
        if(newRels.size() >0){
            this.roleMapper.batchAddMenuRel(newRels);
        }
        if(invalidRels.size() >0){
            this.roleMapper.batchInvalid(uId,invalidRels);
        }
        if(validRels.size() >0){
            this.roleMapper.batchValid(uId,validRels);
        }
        return true;
    }

    /**
     * 查询所有角色
     * @return
     */
    @Override
    public List<Role> listRoles() {
        return this.roleMapper.listRoles();
    }

    @Override
    public Role getByRoleId(Long roleId){
        List<Map<String,Object>> roleMapList = this.roleMapper.getByRoleId(roleId);
        List<Menu> menusList = new ArrayList<Menu>();
        Role role = new Role();
        if(roleMapList != null && roleMapList.size() >0){
            for(Map roleMap : roleMapList){
                Menu menu = new Menu();
                menu.setCode((String) roleMap.get("menuCode"));
                menu.setName((String) roleMap.get("menuName"));
                menu.setPCode((String) roleMap.get("pCode"));
                menu.setType((Integer) roleMap.get("type"));
                menu.setState((Integer) roleMap.get("menuState"));
                menusList.add(menu);
            }
            Map roleMap = roleMapList.get(0);
            role.setAuthorized((Integer) roleMap.get("authorized"));
            role.setDescription((String) roleMap.get("description"));
            role.setId((Long) roleMap.get("id"));
            role.setName((String) roleMap.get("name"));
            role.setState((Integer) roleMap.get("state"));
            role.setMenuList(menusList);
        }else{
           role = roleMapper.queryById(roleId);
        }
        return role;
    }
}
